package com.s2.m.btchat;

import java.io.DataInputStream;

/**
 * Receives messages from remote device
 * @author Samik Sevice
 */
public class MessageReceiver implements Runnable {

    private DataInputStream dis;
    private String message;
    private ChatHandler parent;

    public MessageReceiver(ChatHandler parent, DataInputStream dis) {
        this.parent = parent;
        this.dis = dis;
    }

    public void run() {
        int count = 0;
        try {
            //receive the first message
            message = dis.readUTF();
            //make the chat screen visible (in case of server)
            parent.firstMessageReceived();
            //show the message
            parent.MessageReceived(message);

            //continue receiving messages
            while (true) {
                System.out.println("loop count:" + count++);
                message = dis.readUTF();
                parent.MessageReceived(message);
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }

        //then let the Chat Handler know msg receiver ended
        parent.cannotReceive();

    }
}
